<?php
/**
 * Date: 2024.8
 * Author: kahn
 */
namespace service\uc\oauth;

class WeixinPcClient extends BaseAuthClient{

    private $auth_url = "https://open.weixin.qq.com/connect/qrconnect?";
    private $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private $userInfo_url ="https://api.weixin.qq.com/sns/userinfo";

    //微信扫码登录
    public function getAuthorizeUrl($callbackUrl)
    {
        $params = array();
        $params['appid'] = $this->config['appId'];
        $params['response_type'] = 'code';
        $params['redirect_uri'] = $callbackUrl;
        $params['scope'] = "snsapi_login";
        $params["state"] = "STATE"."#wechat_redirect";

        return $this->auth_url . $this->ToUrlParams($params) ;

    }

    public function getAccessToken($code, $callbackUrl='')
    {
        $params = array(
            'appid' => $this->config['key'],
            'secret' => $this->config['secret'],
            'code' => $code,
            'grant_type' => 'authorization_code'
        );
        $result = $this->getRequest($this->access_token_url, $params);

        $rawToken = json_decode($result, true);
        \Log::info("getAccessToken info", $rawToken);
        if(isset($rawToken['errcode'])){
            \Log::error("getAccessToken is Error",$rawToken);
            return ['error'=>$rawToken['errcode']];
        }
        return $rawToken;
    }

    public function getUserInfo($token){
        $params = array(
            'openid' => $token['openid'] ,
            'access_token' => $token['access_token']
        );
        $result = $this->getRequest($this->userInfo_url, $params);
        $info = json_decode($result, true);
        if(!$info){
            \Log::error("wxpc getAccessToken is Error",$token);
            return null;
        }
        $userInfo = $this->convertUserInfo($info);
        $userInfo['unionId'] = $token['unionid'];

        return $userInfo;
    }

    private function convertUserInfo ($infos) {
        $userInfo = array();
        $userInfo['nickname'] = $infos['nickname'];
        $userInfo['avatar'] = $infos['headimgurl'];
        return $userInfo;
    }

}